package com.joinlink.omiis.commons.persistence.impl;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.joinlink.omiis.commons.persistence.api.IDBProcessor;
import com.joinlink.omiis.commons.persistence.test.Test1;

public class DBProcessor<T> extends AbstractDBProcessor implements IDBProcessor<T> {

	public DBProcessor() {
	}

	private static final Logger logger = LoggerFactory.getLogger(DBProcessor.class);

	@Override
	public int batch(String sql, Object[][] params) throws SQLException, Exception {
		return execBatach(sql, params);
	}

	@Override
	public List query2(String sql, Class type, Object... params) throws Exception {
		return execQuery2(sql, type, params);
	}

	@Override
	public List query(String sql, Object... params) throws Exception {
		return execQuery(sql, params);
	}

	@Override
	public int update(String sql, Object... params) throws Exception {
		return execUpdate(sql, params);
	}

	@Override
	public int delete(String sql, Object... params) throws Exception {
		return execUpdate(sql, params);
	}

	@Override
	public int insert(String sql, Object... params) throws Exception {
		return execUpdate(sql, params);
	}

	@Override
	public int insert(String tableName, T bean) throws Exception {
		Field[] fields = bean.getClass().getDeclaredFields();
		StringBuffer sqlStament = new StringBuffer();
		StringBuffer placeholderStatment = new StringBuffer();
		placeholderStatment.append(" values (");
		sqlStament.append("insert into ").append(tableName).append("(");
		List<String> columns = new ArrayList<>();
		for (int i = 0; i < fields.length; i++) {
			String propertyName = fields[i].getName();
			sqlStament.append(propertyName);
			placeholderStatment.append("?");
			if (i < fields.length - 1) {
				sqlStament.append(",");
				placeholderStatment.append(",");
			}
			columns.add(propertyName);
		}
		sqlStament.append(")");
		placeholderStatment.append(")");
		sqlStament.append(placeholderStatment);
		logger.info("table：" + tableName + "，-insert-sql：" + sqlStament.toString());
		return execInsert(sqlStament.toString(), bean, columns.toArray(new String[] {}));
	}

	@Override
	public int insert(T bean) throws Exception {
		return insert(bean.getClass().getSimpleName(), bean);
	}

}
